package com.jerry.wschat.service;

import com.jerry.wschat.dao.BaseDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.io.Serializable;
import java.util.List;

/**
 * @author Jerry.Wu
 * @description:
 * @date 2018/9/12 18:36
 */
public class BaseServiceImpl <T, ID extends Serializable> implements BaseService<T, ID> {

    @Autowired
    private BaseDao<T, ID> baseDao;

    protected Logger mLogger = LoggerFactory.getLogger(this.getClass());

    public BaseServiceImpl() {

    }

    public BaseDao<T, ID> getDao() {
        return baseDao;
    }

    /**
     * 将MySQL的limit的offset、limit参数转化为Pageable的page、size,同时加入排序字段properties
     * @param limit 个数
     * @param offset 偏移量
     * @param properties 排序字段
     * @return
     */
    public static Pageable getPageable(Integer limit, Integer offset, String properties, Sort.Direction direction) {
        int page = offset / limit;
        int size = limit;
        Sort sort = new Sort(direction, properties);
        return PageRequest.of(page, size, sort);
    }

    @Override
    public void delete(T entity) {
        getDao().delete(entity);
    }

    @Override
    public void deleteById(ID id) {
        getDao().deleteById(id);
    }

    @Override
    public T save(T entity) {
        return getDao().save(entity);
    }

    @Override
    public T load(ID id) {
        return getDao().getOne(id);
    }

    @Override
    public List<T> findAll() {
        return getDao().findAll();
    }

    @Override
    public List<T> findAll(Sort sort) {
        return getDao().findAll(sort);
    }

    @Override
    public Page<T> pageAll(Integer limit, Integer offset, String orderBy, String directionStr) {
        Sort.Direction direction;
        if (directionStr.equals("ASC")) {
            direction = Sort.Direction.ASC;
        } else {
            direction = Sort.Direction.DESC;
        }
        Pageable pageable = getPageable(limit, offset, orderBy, direction);
        return getDao().findAll(pageable);
    }

}
